package cn.com.czpb.client.module.notepad;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.RequiresPermission;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iflytek.sunflower.FlowerCollector;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.czpb.client.R;
import cn.com.czpb.client.app.ToolBarActivity;
import cn.com.czpb.client.model.notepad.NotePadChangeEvent;
import cn.com.czpb.client.model.notepad.NotePdeBean;
import cn.com.czpb.client.module.MainActivity;
import cn.com.czpb.client.utils.JsonParser;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.TUtils;
import cn.com.czpb.client.utils.TimeUtils;
import de.greenrobot.event.EventBus;
import rx.functions.Action1;

public class InputNotepadActivity extends ToolBarActivity {
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_finish)
    TextView tv_finish;
    @BindView(R.id.et_notepad)
    EditText et_notepad;
    @BindView(R.id.img_yuyin)
    ImageView img_yuyin;

    long id;
    String time;
    String content;
    String currentTime;
    private int type;
    NotePadChangeEvent event;


    // 初始化识别无UI识别对象
    // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
    // 语音听写对象
    private SpeechRecognizer mIat;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    // 语音听写UI
    private RecognizerDialog mIatDialog;

    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();

    private String PERMISSION = Manifest.permission.RECORD_AUDIO;

    @Override
    public int setMyContentView() {
        return R.layout.activity_input_notepad;
    }

    @Override
    public void initData() {
        super.initData();
        setToolBarVisiable(true);
        mIat = SpeechRecognizer.createRecognizer(activity, mInitListener);
        mIatDialog = new RecognizerDialog(activity, mInitListener);


        time = getIntent().getStringExtra("time");
        id = getIntent().getLongExtra("id", 1);
        content = getIntent().getStringExtra("content");
        type = getIntent().getIntExtra("type", 0);

        LogUtils.i("time111111111--" + time + "--content--" + content + "--type--" + type + "--" + id);

        currentTime = getTime();
        if (TextUtils.isEmpty(time)) {

            tv_time.setText(getTime());
        } else {
            tv_time.setText(time);
        }

        et_notepad.setText(content);

        et_notepad.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    tv_finish.setVisibility(View.VISIBLE);
                } else {
                    tv_finish.setVisibility(View.GONE);
                }
            }
        });
        et_notepad.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    tv_finish.setVisibility(View.VISIBLE);


                    ;
                } else {
                    tv_finish.setVisibility(View.GONE);
                }
            }
        });


        tv_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(et_notepad.getText().toString())) {
                    TUtils.toast("请输入内容");
                    return;
                }
                if (type == 0) {
                    //添加
                    NotePdeBean bean = new NotePdeBean();
                    bean.setContent(et_notepad.getText().toString());
                    bean.setTime(currentTime);
                    bean.setType(1);

                    bean.save();

                } else {

//                    LitePal.delete(NotePdeBean.class, id);
                    LitePal.deleteAll(NotePdeBean.class,"time=?",time);
//                    DataSupport.deleteAll(NotePdeBean.class);

                    NotePdeBean bean = new NotePdeBean();
                    bean.setContent(et_notepad.getText().toString());
                    bean.setTime(currentTime);
                    bean.setType(1);

                    bean.save();

                }
                event = new NotePadChangeEvent();
                event.setChange(true);
                EventBus.getDefault().post(event);
                finish();
            }
        });


    }

    @OnClick(R.id.img_yuyin)
    public void OnClick(View view) {
        RxPermissions.getInstance(activity)
                .request(PERMISSION)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        LogUtils.i("granted-->" + granted);
                        if (!granted) {
                            new android.app.AlertDialog.Builder(activity)
                                    .setTitle("应用缺少录音权限,请授权")
                                    .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            // 帮跳转到该应用的设置界面，让用户手动授权
                                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                            Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                                            intent.setData(uri);
                                            startActivity(intent);
                                        }
                                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });

                        } else {
                            startVoice();
                        }
                    }
                });


    }

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {

            printResult(results);

        }

        /**
         * 识别回调错误.
         */
        public void onError(SpeechError error) {

            showTip(error.getPlainDescription(true)
            );
        }

    };

    private void startVoice() {
        // 移动数据分析，收集开始听写事件
        FlowerCollector.onEvent(activity, "iat_recognize");
        mIatResults.clear();
        // 设置参数
        setParam();
        // 显示听写对话框
        mIatDialog.setListener(mRecognizerDialogListener);
        mIatDialog.show();
        Toast.makeText(activity, "请开始说话", Toast.LENGTH_LONG).show();
    }


    private void printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());

        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();

        for (String key : mIatResults.keySet()) {

            resultBuffer.append(mIatResults.get(key));
        }
        et_notepad.setText(resultBuffer);
        et_notepad.setSelection(resultBuffer.length());

    }


    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
                showTip("初始化失败，错误码：" + code);
            }
        }
    };

    /**
     * 参数设置
     *
     * @return
     */
    public void setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

//        this.mTranslateEnable = mSharedPreferences.getBoolean( this.getString(R.string.pref_key_translate), false );
//        if( mTranslateEnable ){
//            Log.i( TAG, "translate enable" );
//            mIat.setParameter( SpeechConstant.ASR_SCH, "1" );
//            mIat.setParameter( SpeechConstant.ADD_CAP, "translate" );
//            mIat.setParameter( SpeechConstant.TRS_SRC, "its" );
//        }

//        String lag = mSharedPreferences.getString("iat_language_preference",
//                "mandarin");
//        if (lag.equals("en_us")) {
//            // 设置语言
//            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
//            mIat.setParameter(SpeechConstant.ACCENT, null);
//
//            if( mTranslateEnable ){
//                mIat.setParameter( SpeechConstant.ORI_LANG, "en" );
//                mIat.setParameter( SpeechConstant.TRANS_LANG, "cn" );
//            }
//        } else {
        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        // 设置语言区域
        mIat.setParameter(SpeechConstant.ACCENT, "zh_cn");

//            if( mTranslateEnable ){
//                mIat.setParameter( SpeechConstant.ORI_LANG, "cn" );
//                mIat.setParameter( SpeechConstant.TRANS_LANG, "en" );
//            }
//        }

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, "4000");

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, "1000");

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "0");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav");
    }


    private void showTip(final String str) {
        TUtils.toast(str);
    }

    public String getTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        return df.format(new Date());
    }

    public long getCurrentId() {
        long id = System.currentTimeMillis();
        return id;
    }
}
